package copilot

import (
	"bytes"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"io"
	"net/http"
	"os"
)

func codeCompletions(ctx *gin.Context) {
	data, err := io.ReadAll(ctx.Request.Body)
	if err != nil {
		ctx.JSON(400, gin.H{"error": "Invalid request body"})
		return
	}
	targetModels := "deepseek-coder"
	repPredata := make(map[string]interface{})
	err = json.Unmarshal(data, &repPredata)
	if err != nil {
		ctx.JSON(400, gin.H{"error": err.Error()})
		return
	}
	repPredata["model"] = targetModels
	data, _ = json.Marshal(repPredata)
	url := "https://api.deepseek.com/beta/completions"
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(data))
	if err != nil {
		ctx.JSON(400, gin.H{"error": err.Error()})
		return
	}
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer "+os.Getenv("token"))
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		ctx.JSON(400, gin.H{"error": err.Error()})
		return
	}
	defer resp.Body.Close()
	respData, err := io.ReadAll(resp.Body)
	if err != nil {
		ctx.JSON(400, gin.H{"error": err.Error()})
		return
	}
	ctx.Data(http.StatusOK, resp.Header.Get("Content-Type"), respData)
}
